package com.bookocean.domain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bookocean.application.resp.WechatLoginResp;
import com.bookocean.controller.dto.UserInfoDto;
import com.bookocean.domain.service.UserInfoDomainService;
import com.bookocean.infrastructure.persistence.mapper.UserInfoMapper;
import com.bookocean.infrastructure.persistence.po.UserInfoPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author gaoxing
 * @date 2025-08-18 19:48:01
 */
@Service
@Slf4j
public class UserInfoDomainServiceImpl implements UserInfoDomainService {


    @Autowired
    private UserInfoMapper userMapper;
    @Override
    public UserInfoDto getUserByOpenid(WechatLoginResp response) {
        String openid = response.getOpenid();
        String sessionKey = response.getSessionKey();
        try {
            QueryWrapper<UserInfoPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("openid", openid);
            UserInfoPO user = userMapper.selectOne(queryWrapper);
            if (user == null) {
                user = new UserInfoPO();
                user.setOpenid(openid);
                user.setSessionKey(sessionKey);
                user.setCreateTime(LocalDateTime.now());
                userMapper.insert(user);
                UserInfoPO userInfo = userMapper.selectOne(queryWrapper);
                UserInfoDto userInfoDto = BeanUtil.copyProperties(userInfo, UserInfoDto.class);
                userInfoDto.setNewUser(true);
                return userInfoDto;
            }
            user.setLastLoginTime(LocalDateTime.now());
            userMapper.updateById(user);
            return BeanUtil.copyProperties(user, UserInfoDto.class);
        } catch (Exception e) {
            log.error("根据 OpenID 获取用户信息异常，openid: {}", openid, e);
            return new UserInfoDto();
        }
    }

    @Override
    public UserInfoDto updateUserAvatar(UserInfoDto userInfoDto) {
        log.info("更新用户头像，用户ID: {}", userInfoDto.getId());
        LambdaUpdateWrapper<UserInfoPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(UserInfoPO::getAvatarUrl, userInfoDto.getAvatarUrl());
        updateWrapper.set(UserInfoPO::getNickName, userInfoDto.getNickName());
        updateWrapper.set(UserInfoPO::getGender, userInfoDto.getGender());
        updateWrapper.set(UserInfoPO::getUpdateTime, LocalDateTime.now());
        updateWrapper.eq(UserInfoPO::getId, userInfoDto.getId());
        userMapper.update(null, updateWrapper);
        return userInfoDto;
    }
}
